package com.cola.colaboot.config.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cola.colaboot.config.dto.Res;
import com.cola.colaboot.module.system.pojo.SysAccess;
import com.cola.colaboot.module.system.pojo.SysUser;
import com.cola.colaboot.utils.JwtUtils;
import com.cola.colaboot.utils.MenuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**  
     * 登录成功执行的操作.
     */
    @Override
    @Transactional
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth){
       try {
           SysUser user = (SysUser) auth.getPrincipal();
           String token = JwtUtils.createJWT(user.getId()+"",user.getUsername());

           redisTemplate.opsForValue().set(token,user,30,TimeUnit.MINUTES);         //数据库存未排序的菜单权限，方便校验权限
           user.setAuthorities(MenuUtil.setTreeRemoveMethod((List<SysAccess>) user.getAuthorities()));//返回给客户端排序后的菜单
           user.setPassword(null);

           response.setHeader("token",token);
           Cookie cookie = new Cookie("token", token);
           cookie.setPath("/");
           response.addCookie(cookie);
           PrintWriter writer = response.getWriter();
           JSONObject jsonUser = JSON.parseObject(JSONObject.toJSONString(user));
           jsonUser.put("token",token);
           writer.write(JSONObject.toJSONString(Res.ok("登录成功",jsonUser)));
           writer.flush();
       }catch (Exception e) {
           e.printStackTrace();
       }
    }
}

